import { invoke } from '@tauri-apps/api/core'

/**
 * 配置管理器 - 统一管理账号配置和合约配置
 * 所有配置文件都保存在当前运行目录下的config文件夹中
 */
export class ConfigManager {
  private static readonly CONFIG_DIR = 'config'
  private static readonly ACCOUNT_CONFIG_FILE = 'accounts.json'
  private static readonly CONTRACT_CONFIG_FILE = 'contracts.json'
  private static readonly TRADING_PANEL_CONFIG_FILE = 'td_config.xml'
  private static readonly ACCOUNT_XML_CONFIG_FILE = 'accounts_config.xml'

  /**
   * 确保config目录存在
   */
  private static async ensureConfigDirectory(): Promise<void> {
    try {
      await invoke('ensure_directory', { dirPath: `./${this.CONFIG_DIR}` })
    } catch (error) {
      throw new Error(`创建config目录失败: ${error}`)
    }
  }

  /**
   * 检查配置文件是否存在
   */
  private static async configFileExists(filename: string): Promise<boolean> {
    try {
      return await invoke('path_exists', { path: `./${this.CONFIG_DIR}/${filename}` })
    } catch (error) {
      return false
    }
  }

  /**
   * 保存账号配置
   */
  static async saveAccountConfig(accountConfig: any): Promise<void> {
    try {
      
      // 确保config目录存在
      await this.ensureConfigDirectory()

      // 读取现有的账号配置
      let accounts: Record<string, any> = {}
      try {
        const existingConfig = await invoke('read_config_file', { 
          filename: this.ACCOUNT_CONFIG_FILE 
        }) as string
        accounts = JSON.parse(existingConfig)
      } catch (error) {
        accounts = {}
      }

      // 添加或更新账号配置
      accounts[accountConfig.accountName] = {
        ...accountConfig,
        updateTime: new Date().toISOString()
      }

      // 保存到config文件夹
      const configContent = JSON.stringify(accounts, null, 2)
      const savedPath = await invoke('save_config_file', {
        filename: this.ACCOUNT_CONFIG_FILE,
        content: configContent
      }) as string

    } catch (error) {
      throw new Error(`保存账号配置失败: ${error}`)
    }
  }

  /**
   * 读取所有账号配置
   */
  static async getAllAccountConfigs(): Promise<Record<string, any>> {
    try {
      
      // 检查配置文件是否存在
      const exists = await this.configFileExists(this.ACCOUNT_CONFIG_FILE)
      if (!exists) {
        return {}
      }

      // 读取配置文件
      const configContent = await invoke('read_config_file', { 
        filename: this.ACCOUNT_CONFIG_FILE 
      }) as string

      const accounts = JSON.parse(configContent)
      return accounts
    } catch (error) {
      return {}
    }
  }

  /**
   * 读取单个账号配置
   */
  static async getAccountConfig(accountName: string): Promise<any | null> {
    try {
      const accounts = await this.getAllAccountConfigs()
      return accounts[accountName] || null
    } catch (error) {
      return null
    }
  }

  /**
   * 删除账号配置
   */
  static async deleteAccountConfig(accountName: string): Promise<void> {
    try {
      
      const accounts = await this.getAllAccountConfigs()
      delete accounts[accountName]

      // 保存更新后的配置
      const configContent = JSON.stringify(accounts, null, 2)
      await invoke('save_config_file', {
        filename: this.ACCOUNT_CONFIG_FILE,
        content: configContent
      })

    } catch (error) {
      throw new Error(`删除账号配置失败: ${error}`)
    }
  }

  /**
   * 保存合约配置
   */
  static async saveContractConfig(contractConfig: any): Promise<void> {
    try {
      
      // 确保config目录存在
      await this.ensureConfigDirectory()

      // 读取现有的合约配置
      let contracts: Record<string, any> = {}
      try {
        const existingConfig = await invoke('read_config_file', { 
          filename: this.CONTRACT_CONFIG_FILE 
        }) as string
        contracts = JSON.parse(existingConfig)
      } catch (error) {
        contracts = {}
      }

      // 添加或更新合约配置
      const contractKey = contractConfig.code || contractConfig.contractCode
      contracts[contractKey] = {
        ...contractConfig,
        updateTime: new Date().toISOString()
      }

      // 保存到config文件夹
      const configContent = JSON.stringify(contracts, null, 2)
      const savedPath = await invoke('save_config_file', {
        filename: this.CONTRACT_CONFIG_FILE,
        content: configContent
      }) as string

    } catch (error) {
      throw new Error(`保存合约配置失败: ${error}`)
    }
  }

  /**
   * 读取所有合约配置
   */
  static async getAllContractConfigs(): Promise<Record<string, any>> {
    try {
      
      // 检查配置文件是否存在
      const exists = await this.configFileExists(this.CONTRACT_CONFIG_FILE)
      if (!exists) {
        return {}
      }

      // 读取配置文件
      const configContent = await invoke('read_config_file', { 
        filename: this.CONTRACT_CONFIG_FILE 
      }) as string

      const contracts = JSON.parse(configContent)
      return contracts
    } catch (error) {
      return {}
    }
  }

  /**
   * 读取单个合约配置
   */
  static async getContractConfig(contractCode: string): Promise<any | null> {
    try {
      const contracts = await this.getAllContractConfigs()
      return contracts[contractCode] || null
    } catch (error) {
      return null
    }
  }

  /**
   * 删除合约配置
   */
  static async deleteContractConfig(contractCode: string): Promise<void> {
    try {
      
      const contracts = await this.getAllContractConfigs()
      delete contracts[contractCode]

      // 保存更新后的配置
      const configContent = JSON.stringify(contracts, null, 2)
      await invoke('save_config_file', {
        filename: this.CONTRACT_CONFIG_FILE,
        content: configContent
      })

    } catch (error) {
      throw new Error(`删除合约配置失败: ${error}`)
    }
  }

  /**
   * 清空所有配置
   */
  static async clearAllConfigs(): Promise<void> {
    try {
      
      // 清空账号配置
      await invoke('save_config_file', {
        filename: this.ACCOUNT_CONFIG_FILE,
        content: JSON.stringify({}, null, 2)
      })

      // 清空合约配置
      await invoke('save_config_file', {
        filename: this.CONTRACT_CONFIG_FILE,
        content: JSON.stringify({}, null, 2)
      })

    } catch (error) {
      throw new Error(`清空配置失败: ${error}`)
    }
  }

  /**
   * 获取配置目录信息
   */
  static async getConfigInfo(): Promise<{
    configDir: string
    accountConfigExists: boolean
    contractConfigExists: boolean
    accountCount: number
    contractCount: number
  }> {
    try {
      const accountExists = await this.configFileExists(this.ACCOUNT_CONFIG_FILE)
      const contractExists = await this.configFileExists(this.CONTRACT_CONFIG_FILE)

      const accounts = await this.getAllAccountConfigs()
      const contracts = await this.getAllContractConfigs()

      return {
        configDir: `./${this.CONFIG_DIR}`,
        accountConfigExists: accountExists,
        contractConfigExists: contractExists,
        accountCount: Object.keys(accounts).length,
        contractCount: Object.keys(contracts).length
      }
    } catch (error) {
      return {
        configDir: `./${this.CONFIG_DIR}`,
        accountConfigExists: false,
        contractConfigExists: false,
        accountCount: 0,
        contractCount: 0
      }
    }
  }

  /**
   * 保存任意配置文件到config文件夹
   */
  static async saveConfigFile(filename: string, content: string): Promise<string> {
    try {

      await this.ensureConfigDirectory()

      const savedPath = await invoke('save_config_file', {
        filename,
        content
      }) as string

      return savedPath
    } catch (error) {
      throw new Error(`保存配置文件失败: ${error}`)
    }
  }

  /**
   * 从config文件夹读取任意配置文件
   */
  static async readConfigFile(filename: string): Promise<string> {
    try {

      const content = await invoke('read_config_file', {
        filename
      }) as string

      return content
    } catch (error) {
      throw new Error(`读取配置文件失败: ${error}`)
    }
  }

  /**
   * 保存交易面板配置（XML格式）
   */
  static async saveTradingPanelConfig(xmlContent: string): Promise<string> {
    try {
      return await this.saveConfigFile(this.TRADING_PANEL_CONFIG_FILE, xmlContent)
    } catch (error) {
      throw new Error(`保存交易面板配置失败: ${error}`)
    }
  }

  /**
   * 读取交易面板配置（XML格式）
   */
  static async readTradingPanelConfig(): Promise<string> {
    try {
      return await this.readConfigFile(this.TRADING_PANEL_CONFIG_FILE)
    } catch (error) {
      throw new Error(`读取交易面板配置失败: ${error}`)
    }
  }

  /**
   * 保存账号配置（XML格式）
   */
  static async saveAccountConfigXML(xmlContent: string): Promise<string> {
    try {
      return await this.saveConfigFile(this.ACCOUNT_XML_CONFIG_FILE, xmlContent)
    } catch (error) {
      throw new Error(`保存账号配置XML失败: ${error}`)
    }
  }

  /**
   * 读取账号配置（XML格式）
   */
  static async readAccountConfigXML(): Promise<string> {
    try {
      return await this.readConfigFile(this.ACCOUNT_XML_CONFIG_FILE)
    } catch (error) {
      throw new Error(`读取账号配置XML失败: ${error}`)
    }
  }
}
